package com.haotian.coder.manager;

import com.haotian.coder.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.io.File;

@Slf4j
@Component
@ConditionalOnBean(COSClient.class)
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private COSClient cosClient;


    /**
     * 上传对象
     * @param key
     * @param file
     * @return
     */
   public PutObjectResult putObject(String key, File file){
       PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
       return cosClient.putObject(putObjectRequest);
   }


    /**
     * 上传文件
     * @param key
     * @param file
     * @return
     */
   public String upLoadFile(String key ,File file){
       PutObjectResult putObjectResult = putObject(key, file);
       if (putObjectResult!= null){
           String url = cosClientConfig.getHost() + "/" + key;
           log.info("上传文件成功，文件地址为：{}", url);
           return url;
       }else{
           log.error("上传文件失败,返回结果为空");
           return null;
       }
   }

}
